package com.shloma.bbts.controller;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.shloma.bbts.controller.support.AbstractSubPageController;
import com.shloma.bbts.entity.AreaAcct;
import com.shloma.bbts.service.AreaAcctService;
import com.shloma.bbts.utils.AlertUtil;
import com.shloma.bbts.utils.BeanFactoryUtils;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

/**
 * 新增区划信息
 * <p>
 *
 * @author xuefeng.shi
 * @date 2018/12/07
 * @version v1.0.0
 */
public class AddAreaAcctController extends AbstractSubPageController {

	private static Logger logger = LoggerFactory.getLogger(AddAreaAcctController.class);
	private AreaAcctService acctService;

	@FXML
	private TextField rgnCde;
	@FXML
	private TextField rgnNme;
	@FXML
	private TextField mainAcct;
	@FXML
	private TextField mainAcctNme;

	@FXML
	private Button addAreaAcctBtn;

	@FXML
	public void addAreaAcct() {

		String inputRgnCde = rgnCde.getText();
		String inputRngNme = rgnNme.getText();
		if (StringUtils.isEmpty(inputRgnCde) || StringUtils.isEmpty(inputRngNme)) {
			logger.error("##### 必输项为空 rgnCde:{} rgnNme:{}", inputRgnCde, inputRngNme);
			AlertUtil.showWarnAlert("必输项为空", "行政区划代码和行政区划名称字段必输,请检查");
			return;
		}

		AreaAcct queryAreaAcct = new AreaAcct();
		queryAreaAcct.setRgnCde(inputRgnCde);
		List<AreaAcct> areaAcct = acctService.getAreaAcctsByQueryCondition(queryAreaAcct);
		if (!CollectionUtils.isEmpty(areaAcct)) {
			logger.error("##### 新增的行政区信息已经存在 rgnCde:{}", inputRgnCde);
			AlertUtil.showWarnAlert("新增行政区划信息", "新增的行政区信息已经存在,请勿重复添加");
		} else {

			queryAreaAcct.setRgnNme(inputRngNme);
			queryAreaAcct.setMainAcct(mainAcct.getText());
			queryAreaAcct.setMainAcctNme(mainAcctNme.getText());
			acctService.addAreaAcct(queryAreaAcct);

			ConfigManagerController configManagerController = (ConfigManagerController) getParentController();
			configManagerController.queryAccts();
			configManagerController.initRgnCdeChoiceBox();

			Stage stage = (Stage) addAreaAcctBtn.getScene().getWindow();
			stage.close();
		}
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see javafx.fxml.Initializable#initialize(java.net.URL,
	 *      java.util.ResourceBundle)
	 */
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		logger.info(">>>>>> 初始化添加行政区划主账号界面");
		acctService = BeanFactoryUtils.getBean(AreaAcctService.class);
	}

}
